<template>
    <div class="askLeaveEditor" v-if="hasRight">
        <div class="askLeaveTitle">干部请假
            <van-tag plain color="blue" style="font-size: 14px;padding:5px 10px;position: absolute;right: 10px;">拟稿</van-tag>
        </div>

        <div class="editorSectionTitle">个人信息</div>
      
          

        <van-form  required="auto" label-width="90px" ref="formRef" show-error show-error-message	>
            <van-cell-group inset style="padding-top:10px;">
                <van-field v-model="form.author"   label="姓名" placeholder="" readonly />
                <van-field v-model="authCollege"   label="工作单位" placeholder="" readonly :is-link="canSelectCollege" @click="handleCollegeClick" arrow-direction="down" />
                <van-field v-model="form.tpost"   label="职务" placeholder="" readonly />            
                <van-field v-model="form.cellPhone" name="cellPhone"   label="手机" placeholder="请输入手机号" readonly size="large" :rules="[{ required: true }]"/>
                <van-field v-model="form.workPhone"   label="固定电话" placeholder="请输入" readonly size="large" :rules="[{ required: false }]"/>
                <van-field v-model="form.email"   label="Email" placeholder="请输入" readonly size="large" :rules="[{ required: false }]"/>                
            </van-cell-group>
            <div class="editorSectionTitle">请假信息</div>                
            <van-cell-group inset style="padding-top:10px;">
                <van-field v-model="leavetype"   name="leaveType"  arrow-direction="down"   is-link readonly   label="任务类别" placeholder="请选择任务类别" @click="showSelectLeavetype = true" :rules="[{ required: true }]"/>
                <van-field v-model="form.leaveDest"  name="leaveDest" label="前往城市或国家"  label-align="top" placeholder="请填写前往城市或国家"  class="leaveDestInput"
                 size="large"  :rules="[{ required: true }]"/>
                <van-field v-model="duration" is-link readonly  arrow-direction="down"  name="beginEnd" label-align="top"  label="期限" placeholder="请选择出发返回日期"
                class="duration"
                 @click="showBegin = true" size="large" :rules="[{ required: true }]">               
                </van-field>
                <van-field v-model="form.leaveDays"  name="leaveDays"  label="请假天数" placeholder="请输入"   type="number" size="large" :rules="[{ required: true }]"/>
                <van-field v-model="form.content" name="content"  label-align="top" rows="1" autosize label="外出事由" type="textarea"  class="askleaveReason"
                placeholder="请输入外出事由" size="large" :rules="[{ required: true }]"/>
                <van-field name="leaveFee" label="经费来源" size="large"  label-align="top" :rules="[{ required: true }]">
                    <template #input>                        
                        <div class="leaveFeeGroup">
                            <van-checkbox name="1" shape="square" class="feeCheckItem" v-model:model-value="form.leaveSchoolFee">
                                <template #default>
                                    学校经费
                                </template>
                            </van-checkbox>
                            <div class="feeCheckItemContent" v-if="form.leaveSchoolFee">
                                由<input class="feeInput" v-model="form.leaveSchoolFeeType" placeholder="请输入">经费支付<input class="feeInput" v-model="form.leaveSchoolFeeUsage" placeholder="请输入">费用
                                <div class="feeitemRemark">（如：由 <span class="underline">横向科研</span> 经费支付 <span class="underline">出差</span> 费用）</div>
                            </div>
                            <van-checkbox name="2" shape="square" class="feeCheckItem" v-model="form.leaveInvitorFee">邀请方支付</van-checkbox>
                            <div class="feeCheckItemContent" v-if="form.leaveInvitorFee">
                                支付<input class="feeInput w200" v-model="form.leaveInvitorFeeUsage" placeholder="请输入费用">费用
                                <div class="feeitemRemark">（如：支付  <span class="underline">餐饮住宿</span>  费用）</div>
                            </div>
                            <van-checkbox name="3" shape="square" class="feeCheckItem" v-model="form.leaveOtherFee">其他</van-checkbox>
                            <div class="feeCheckItemContent" v-if="form.leaveOtherFee">
                                <input class="feeInput w200" v-model="form.leaveOtherFeeUsage" placeholder="请输入费用">费用
                                <div class="feeitemRemark">（如：  <span class="underline">个人自费 </span>）</div>
                            </div>
                        </div>
                     </template>
                </van-field>
            </van-cell-group>
        </van-form>

        <div class="editorSectionTitle">附件</div>
        <AttachUploader v-model="form.attachList"/>
        
        <div style="margin: 26px;margin-right: 20px;margin-left: 20px;" class="askLeaveBottomBtnsWrapper">                
                <van-button  class="formOptBtn"   type="primary"   color="#1989fa" @click="handleSave">保存</van-button>
                <van-button   class="formOptBtn"  type="primary" @click="handleSubmit" style="margin-right: 0;">提交</van-button>
        </div>
    </div>

    <div v-if="!hasRight" >
        <div v-if="!loading" class="noCreateRight">您暂无干部请假的权限!</div>
        <div v-if="loading" style="text-align: center;padding:30px">加载中...</div>
    </div>

    <van-popup v-model:show="showSelectLeavetype" destroy-on-close position="bottom">
        <van-picker
            title="选择任务类别"
            :columns="leaveTypes"
            :model-value="getLeaveType"
            :columns-field-names="{text:'value',value:'id'}"
            @confirm="onConfirm"
            @cancel="showSelectLeavetype = false"
        />
    </van-popup>

    <van-calendar v-model:show="showBegin" type="range" :formatter="formatter"  @confirm="onConfirmDuration"/>


    <van-popup v-model:show="showSelectCollege" destroy-on-close round position="bottom">
        <van-picker
            title="请选择工作单位"
            :columns="authCollegeList"
            :columns-field-names="{text:'collegeName',value:'collegeId'}"
            @confirm="onConfirmSelectCollege"
            @cancel="onCancelSelectCollege"
            
        />
    </van-popup>
    

</template>
<script setup lang="ts">

import type { Attach, College, DocForm, Employee } from '@/types/workflow';
import { computed, onMounted, reactive, ref, toRaw } from 'vue';
import { getLeaveTypeById, leaveTypes } from '@/service/DictService';
import http from '@/api/request'
import type { CalendarDayItem, FormInstance, PickerConfirmEventParams } from 'vant';
import AttachUploader from '@/components/attachUploader.vue';
import DialogTool from '@/util/DialogTool';
import { formateDate, getDaysDifference } from '@/util/dateTool';
import { useRoute, useRouter } from 'vue-router';
import type { Numeric } from 'vant/lib/utils';

const router = useRouter();


interface AskLeaveUserInfo{
    emp:Employee
    collegeList:College[]    
}
const getLeaveType = computed(():number[]|undefined=>{
    var result:number[] = [];
    if( form.value.leaveType){
        result.push(form.value.leaveType)
        return result;
    };
})
const  selectCollege = ref<College>();
const authCollege = computed(()=>{
    if(selectCollege.value){
        return selectCollege.value.collegeName;
    }
    return ''
})
const showSelectLeavetype = ref(false)
const showBegin = ref(false)
const showSelectCollege = ref(false)
const formRef = ref<FormInstance>()
const duration = computed(()=>{
    var start = form.value.leaveFromDate;
    var end = form.value.leaveToDate;
    if(start && end){
        return  `${formatDateToShow(start)} - ${formatDateToShow(end)}`;
    }else{
        return ''
    }    
})
const formatDateToShow = (date:string) => {
    console.log(date)
    return date.substring(0,4)+"年"+date.substring(5,7)+"月"+date.substring(8,10)+'日';    
};

const loading = ref(true)
const authCollegeList = ref<College[]>([]);
const route = useRoute();
const hasRight = computed(()=>{
    console.log('has right:'+form.value.id)
    if(form.value.id){//编辑信息
        return true;
    }else{
        //判断授权的学院
        if(authCollegeList.value.length == 0){
            return false;
        }else{
            return true;
        }        
    }
})
 
const formatter = (day:CalendarDayItem) => {
      const month = day.date?.getMonth();
      const date = day.date?.getDate();

    const now = new Date();

      if (month === now.getMonth()) {
        if (date === now.getDate()) {
          day.text = '今天';
        }
      }

      if (day.type === 'start') {
        day.bottomInfo = '出发';
      } else if (day.type === 'end') {
        day.bottomInfo = '返回';
      }

      return day;
};

onMounted(()=>{

    var fid = route.query.fid;
    if(fid){
        loadForm(fid);
    }else{
        loadUserInfo();
    }

  
});
const loadForm = (fid:any)=>{
    http.get<DocForm>('form/get',{fid})
    .then((resp)=>{
        if(resp.data){
            form.value = resp.data;
            getAttachList(resp.data.id);
        }

        selectCollege.value = {
            collegeId:resp.data?.draftCollegeId,
            collegeName:resp.param2
        }
    });
}

const loadUserInfo= ()=>{
    DialogTool.showLoading();
    http.get<AskLeaveUserInfo>('/askleave/userInfo').then((resp)=>{
        DialogTool.closeToast();
        loading.value=false;

        var emp = resp.data?.emp;
        var collegeList = resp.data?.collegeList;
        if(collegeList){
            authCollegeList.value = collegeList;
            if(authCollegeList.value.length == 1){
                selectCollege.value = collegeList[0];
                form.value.draftCollegeId = selectCollege.value.collegeId;

            }else if(authCollegeList.value.length > 1){
                showSelectCollege.value = true;
            }
        }
        
        if(!form.value.id && emp){//初始化信息
            if(emp.name)form.value.author = emp.name;
            if(emp.cellPhone)form.value.cellPhone = emp.cellPhone;
            if(emp.email)form.value.email = emp.email;
            if(emp.apost)form.value.tpost = emp.apost;
            if(emp.workPhone)form.value.workPhone=emp.workPhone;
        }

    }).catch(()=>{
        DialogTool.closeToast();
        loading.value=false;
    })
}

const getAttachList = (formId:any)=>{    
    http.get<Attach[]>('/attach/getbyform',{
        formId
    }).then((resp)=>{
        const list = resp.data;
        if(list){
            form.value.attachList = list;
        }else{
            form.value.attachList = [];
        }        
    })
}

const canSelectCollege = computed(()=>{
    if(authCollege.value?.length && authCollege.value?.length > 1){
        return true;
    }else{
        return false;
    }
})
const handleCollegeClick = ()=>{
    if(canSelectCollege.value){
        showSelectCollege.value = true;
    }
}

const onConfirmSelectCollege =(selectItem:PickerConfirmEventParams)=>{
    var college = authCollegeList.value[selectItem.selectedIndexes[0]];
    selectCollege.value = college;
    form.value.draftCollegeId = college.collegeId;
    showSelectCollege.value= false;
}
const onCancelSelectCollege =()=>{
    if(!form.value.draftCollegeId){//默认为第一个
        var college = authCollegeList.value[0];
        selectCollege.value = college;
        form.value.draftCollegeId = college.collegeId;        
    }
    showSelectCollege.value= false;
}

const onConfirm = (selectItem:PickerConfirmEventParams) => {
    if(typeof(selectItem.selectedValues[0]) == 'number'){
        form.value.leaveType = selectItem.selectedValues[0];
    }
    showSelectLeavetype.value = false;
};

const onConfirmDuration = (values:Date[]) => {
      const [start, end] = values;
      showBegin.value = false;      

      //格式化开始、结束日期给form表单
      form.value.leaveFromDate = formateDate(start);
      form.value.leaveToDate = formateDate(end);

      //计算请假天数
      form.value.leaveDays = getDaysDifference(start,end);
};




const form = ref<DocForm>({
    author:'王旭东',
})
    
const leavetype = computed(()=>{
    console.log('getleaveType:'+form.value.leaveType)
    if(form.value.leaveType){
        var type  = getLeaveTypeById(form.value.leaveType);
        console.log(type)
        if(!type) {
            return ''
        }else{
            return type;
        }
    }else{
        return '';
    }
})



const validateForm = ()=>{

    if(!form.value.cellPhone){
        DialogTool.showToast("请填写手机号")
        formRef.value?.scrollToField('cellphone');
        return false;
    }

    
    if(!form.value.leaveType){
        DialogTool.showToast("请选择任务类别")
        formRef.value?.scrollToField('leaveType');
        formRef.value?.validate('leaveType')
        return false;
    }

    if(!form.value.leaveDest){
        DialogTool.showToast("请填写前往城市或国家")
        formRef.value?.scrollToField('leaveDest');
        formRef.value?.validate('leaveDest')
        return false;
    }

    if(!form.value.leaveFromDate){
        
        DialogTool.showToast("请选择出发返回日期")
        formRef.value?.scrollToField('beginEnd');
        formRef.value?.validate('beginEnd')
        return false;
    }

    if(!form.value.leaveDays){        
        DialogTool.showToast("请填写请假天数")
        formRef.value?.scrollToField('leaveDays');
        formRef.value?.validate('leaveDays')
        return false;
    }

    
    if(!form.value.content){        
        DialogTool.showToast("请填写外出事由")
        formRef.value?.scrollToField('content');
        formRef.value?.validate('content')
        return false;
    }

    if(!form.value.leaveSchoolFee && !form.value.leaveOtherFee && !form.value.leaveInvitorFee){
        DialogTool.showToast("请填写经费来源")
        formRef.value?.scrollToField('leaveFee');
        formRef.value?.validate('leaveFee')
        return false;
    }

    if(form.value.leaveSchoolFee){
        if(!form.value.leaveSchoolFeeType){
            DialogTool.showToast("请填写学校经费类型")
            return false;
        }

        if(!form.value.leaveSchoolFeeUsage){
            DialogTool.showToast("请填写学校经费用途")
            return false;
        }
    }

    

    if(form.value.leaveInvitorFee){
        if(!form.value.leaveInvitorFeeUsage){
            DialogTool.showToast("请填写邀请方支付哪些费用")
            return false;
        }
    }

    
    if(form.value.leaveOtherFee){
        if(!form.value.leaveOtherFeeUsage){
            DialogTool.showToast("请填写关于其他费用的说明")
            return false;
        }
    }    

    return true;
}
const handleSave = ()=>{
    var ret = validateForm();
    if(!ret) return;


    DialogTool.showLoading();

    http.post<DocForm>('/askleave/save',form.value)
    .then((resp)=>{
        var data = resp.data;
        form.value.id = data?.id;
        DialogTool.closeToast();
        DialogTool.showToast("保存成功");
    }).catch((resp)=>{        
        DialogTool.closeToast();
        DialogTool.showAlert("保存失败！");
    });
}

const handleSubmit = ()=>{
    var ret = validateForm();
    if(!ret) return;


    DialogTool.showLoading();

    http.post('/askleave/submit',form.value)
    .then((resp)=>{
        DialogTool.closeToast();
        DialogTool.showAlert("提交成功！可在【我的】-【我的公文】中查看审批情况。")
        .then(()=>{
            router.replace('/doc/my');
        });
    }).catch((resp)=>{        
        DialogTool.closeToast();
        DialogTool.showAlert("保存失败！");
    });
}

</script>
<style lang="less" scoped>
.askLeaveEditor{
    padding-bottom: 50px;
    .askLeaveTitle{
        font-size: 20px;
        font-weight: bold;
        padding:20px;
        padding-bottom: 0px;
    }
}
.feeCheckItem{
    margin-top: 10px;
    margin-bottom: 15px;
}
.feeInput{
    border:none;
    width: 100px;
    border-bottom: 1px solid #d2d2d2;
    text-align: center;
    padding-left: 4px;
    padding-right: 4px;
}

.feeCheckItem .van-checkbox{
    align-items: flex-start;
}
.feeCheckItemContent{
    padding-left: 30px;
}
.feeitemRemark{
    color:#888;
    margin-top: 4px;
}
.leaveFeeGroup{
    display: flex;
    flex-direction: column;
    font-size: 14px;
    padding-left: 10px;
}
.leaveFeeGroup .underline{
    text-decoration: underline;
}
.feeInput.w200{
    width: 200px;
}
.askLeaveBottomBtnsWrapper{
    display: flex;
    .formOptBtn{
        width: 100px;
        flex-grow: 1;
        margin-right: 20px;
        font-size: 16px;
    }
}
.editorSectionTitle{
    margin-left: 10px;
    color:#969799;
    margin-top: 10px;
    margin-bottom: 5px;
    padding: 16px 16px 8px;
    font-size: 14px;
    font-weight: 400;
    line-height: 16px;
}
.noCreateRight{
    text-align: center;
    font-size: 25px;
    margin-top: 100px;    
    padding:30px;
}
</style>
<style lang="css">
.leaveDestInput label{
    width: 130px !important;
}

.leaveDestInput input{
    padding-left: 9px;
}

.askleaveReason textarea{
    padding-left: 9px;
}
.duration input{
    padding-left: 9px;
}
</style>